package handler

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"math/rand"
	"net/http"
	"red/api/request"
	"red/consts"
	"red/global"
	"red/intermal/model"
	"red/pkg"
	"time"
)

func Login(c *gin.Context) {
	param := request.Login{}
	if err := c.ShouldBind(&param); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 400,
			"mes":  "参数错误",
		})
		return
	}
	var users model.User
	global.DB.Model(&model.User{}).Where("tel =?", param.Tel).Find(&users)
	result, _ := global.Rdb.Get(global.Ctx, "sendSms"+param.Tel).Result()
	if result != param.SendCode {
		log.Println("验证码失效")
		fmt.Println("验证码失效")
	}
	token := pkg.Token(uint(users.Id), time.Hour*5, consts.JWT_KEY)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"mes":  "登陆成功",
		"data": token,
	})
}

func SendSms(c *gin.Context) {
	param := request.SendSms{}
	if err := c.ShouldBind(&param); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 400,
			"mes":  "参数错误",
		})
		return
	}
	code := rand.Intn(9000) + 100
	//sms, _ := pkg.SendSms(param.Tel, strconv.Itoa(code))
	//if *sms.Body.Code != "OK" {
	//	fmt.Println(*sms.Body.Message)
	//}
	global.Rdb.Set(global.Ctx, "sendSms"+param.Tel, code, time.Hour*5)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"mes":  "发送短信成功",
		"data": nil,
	})
	return
}

func UserShow(c *gin.Context) {
	param := request.UserShow{}
	if err := c.ShouldBind(&param); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 400,
			"mes":  "参数错误",
		})
		return
	}
	var users model.User
	global.DB.Model(&model.User{}).Where("id=?", param.Id).Find(&users)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"mes":  "详情成功",
		"data": users,
	})
}
